package com.personal.service.Impl;

import com.personal.dao.ShopDao;
import com.personal.dto.ImageHolder;
import com.personal.dto.ShopExecution;
import com.personal.entity.Shop;
import com.personal.enums.ShopStateEnum;
import com.personal.exception.ShopOperationException;
import com.personal.service.ShopService;
import com.personal.utils.FileUtil;
import com.personal.utils.ImageUtil;
import com.personal.utils.PageCalculator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author 萌新
 * @version 1.0
 * @date 2021/4/14 10:22
 */

@Service
public class ShopServiceImpl implements ShopService {

    private static final Logger logger = LoggerFactory.getLogger(ShopServiceImpl.class);

    @Autowired
    private ShopDao shopDao;

    @Override
    public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
        //前台页面插入的pageIndex(第几页)，而dao层使用的是rowIndex(第几行)，所以需要转换一下
        int rowIndex = PageCalculator.calculateRowIndex(pageIndex,pageSize);
        //查询带有分页的shoplist
        List<Shop> shopList = shopDao.queryShopList(shopCondition,rowIndex,pageSize);
        //查询复合条件的shop总数
        int count = shopDao.queryShopCount(shopCondition);
        ShopExecution se = new ShopExecution();
        //将shoplist和count设置到se中，返回给控制层
        if (shopList != null){
            se.setShopList(shopList);
            se.setCount(count);
        }else {
            se.setState(ShopStateEnum.INNER_ERROR.getState());
        }
        return se;
    }

    @Override
    public Shop getByShopId(long shopId) {
        return shopDao.queryByShopId(shopId);
    }

    @Override
    public ShopExecution modifyShop(Shop shop, ImageHolder thumbnail) throws ShopOperationException {
       if (shop == null || shop.getShopId() == null){
           return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
       }else {
           try {
               //1.判断是否需要处理图片
               if (thumbnail.getIns() != null && thumbnail.getFileName() != null) {
                   Shop tempShop = shopDao.queryByShopId(shop.getShopId());
                   //如果之前的店铺里面图片不为空，就先把之前的地址先删掉
                   System.out.println("-----------------------------------------");
                   System.out.println(tempShop.getShopImg());
                   System.out.println("-----------------------------------------");
                   if (tempShop.getShopImg() != null) {
                       ImageUtil.deleteFileOrPath(tempShop.getShopImg());
                   }
                   //删除之后插入新的图片
                   //传入shop是因为tempShop是之前的对象，而shop是根据前端传来的值封装的

                   System.out.println(shop);

                   addShopImg(shop, thumbnail);
               }
               //2.更新店铺信息
               //最新的更改时间
               shop.setLastEditTime(new Date());
               int effectedNum = shopDao.updateShop(shop);
               if (effectedNum <= 0) {
                   return new ShopExecution(ShopStateEnum.INNER_ERROR);
               } else {
                   shop = shopDao.queryByShopId(shop.getShopId());
                   return new ShopExecution(ShopStateEnum.SUCCESS, shop);
               }
           } catch (Exception e) {
               throw new ShopOperationException("modifyShop error:" + e.getMessage());
           }
       }
    }

    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, ImageHolder thumbnail) {
        // 非空判断 (这里先判断shop是否为空，严格意义上讲shop中的are的属性也需要判断)
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }

        // 关键步骤1. 设置基本信息，插入shop
        // 初始状态： 审核中
        shop.setEnableStatus(0);
        shop.setCreateTime(new Date());
        shop.setLastEditTime(new Date());

        int effectedNum = shopDao.insertShop(shop);
        if (effectedNum <= 0) {
            throw new ShopOperationException("创建店铺失败");
        } else {
            // 关键步骤2. 添加成功,则继续处理文件,获取shopid,用于创建图片存放的目录
            if (thumbnail.getIns() != null) {
                try {
                    // 需要根据shopId来创建目录,所以也需要shop这个入参
                    addShopImg(shop, thumbnail);
                } catch (Exception e) {
                    logger.error("addShopImg error {} ", e.toString());
                    throw new ShopOperationException("addShopImg error:" + e.getMessage());
                }
                // 关键步骤3. 更新tb_shop中 shop_img字段
                effectedNum = shopDao.updateShop(shop);
                if (effectedNum <= 0) {
                    logger.error("updateShop error {} ", "更新店铺失败");
                    throw new ShopOperationException("updateShop error");
                }
            }
        }
        // 返回店铺的状态：审核中，以及店铺信息
        return new ShopExecution(ShopStateEnum.CHECK, shop);
    }

    private void addShopImg(Shop shop, ImageHolder thumbnail) {
        String imgPath = FileUtil.getShopImagePath(shop.getShopId());
        // 生成图片的水印图
        String relativeAddr = ImageUtil.generateThumbnails(thumbnail, imgPath);
        // 将相对路径设置个shop,用于更新数据库
        shop.setShopImg(relativeAddr);
    }
}
